<template>
  <div class="app-container">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="title">
        <img 
          class="logo"
          src="../assets/logo.png" 
          alt="logo"
          style="height: 85px; width: 85px;"
        >
        见微知著——面向复杂表格的识别推理
      </div>
      <div class="user-info">
        <img 
          class="avatar"
          src="../assets/avatar.jpeg" 
          alt="avatar"
        >
        <div class="email">cici &lt;1212222@163.com&gt;</div>
      </div>
    </header>

    <!-- 三列主体 -->
    <div class="main-content">
      <!-- 左：文件上传与预览 -->
      <div class="upload-pane">
        <div 
          class="drop-zone"
          @dragover.prevent="dragOver = true"
          @dragleave="dragOver = false"
          @drop.prevent="handleDrop"
          @click="triggerFileInput"
          :class="{ 'hover': dragOver }"
        >
          Paste or drag & drop a file here
        </div>
        <div class="preview-label">上传图片预览</div>
        <div class="preview">
          <img 
            v-if="previewUrl"
            :src="previewUrl" 
            alt="preview"
          >
        </div>
      </div>

      <!-- 中：LaTeX 控件与渲染 -->
      <div class="center-pane">
        <div class="controls">
          <button 
            class="control-btn"
            @click="requestParse('latex')"
          >开始解析
        </button>
          <button 
            class="control-btn"
            @click="changeMode('latex')"
          >
            LaTeX
          </button>
          <button 
            class="control-btn"
            @click="changeMode('render')"
          >
            LaTeX Render
          </button>
        </div>
        <div class="latex-render">
          {{ loading ? '加载中...' : '' }}
          <div v-if="mode === 'latex'" v-html="formattedLatex"></div>
          <img 
            v-else-if="mode === 'render' && renderedImage"
            :src="renderedImage" 
            alt="rendered latex"
          >
        </div>
        <div class="icon-container">
            <svg id="copyIcon" t="1750409156113" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1454" width="200" height="200"><path d="M85.312 85.312H640V320H554.688V170.688h-384v384H320V640H85.312V85.312zM384 384h554.688v554.688H384V384z m85.312 85.312v384h384v-384h-384z" p-id="1455"></path></svg>
          <!-- <svg class="icon" @click="downloadLatex">
            
          </svg> -->
          <svg id="downloadIcon" t="1750409305820" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2448" width="200" height="200"><path d="M505.7 661c3.2 4.1 9.4 4.1 12.6 0l112-141.7c4.1-5.2 0.4-12.9-6.3-12.9h-74.1V168c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v338.3H400c-6.7 0-10.4 7.7-6.3 12.9l112 141.8z" p-id="2449"></path><path d="M878 626h-60c-4.4 0-8 3.6-8 8v154H214V634c0-4.4-3.6-8-8-8h-60c-4.4 0-8 3.6-8 8v198c0 17.7 14.3 32 32 32h684c17.7 0 32-14.3 32-32V634c0-4.4-3.6-8-8-8z" p-id="2450"></path></svg>
        </div>
      </div>

      <!-- 右：问答机器人 -->
      <div class="chat-pane">
        <div class="chat-log">
          <div 
            v-for="(msg, index) in chatMessages" 
            :key="index" 
            class="msg" 
            :class="msg.sender"
          >
            <div class="bubble">
              <img 
                v-if="msg.sender === 'bot'"
                src="https://www.logosc.cn/uploads/icon/2019/04/28/f4d1fd51-0ae8-4159-934c-7830f535f931.png" 
                alt="bot"
              >
              {{ msg.content }}
            </div>
          </div>
        </div>
        <div class="chat-input">
          <!-- <div class="file-upload" @click="triggerChatFileInput">
            <svg class="upload-icon"></svg>
          </div> -->
          <input 
            v-model="newMessage"
            style="height: 45px;"
            type="text" 
            class="chat-text" 
            placeholder="Enter message or upload file..."
            @keypress.enter="sendMessage"
          >
          <button class="send-btn" style="height: 45px;" @click="sendMessage">
            Send
          </button>
        </div>
        <div class="uploaded-files">
          <div 
            v-for="(file, index) in chatFiles" 
            :key="index" 
            class="file-item"
          >
            <span class="file-name">{{ file.name }}</span>
            <button class="remove-btn" @click="removeFile(index)">
              ×
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 隐藏的文件输入 -->
    <input 
      ref="fileInput"
      type="file" 
      class="hidden-input"
      @change="handleFileChange"
    >
    <input 
      ref="chatFileInput"
      type="file" 
      class="hidden-input"
      @change="handleChatFileChange"
      multiple
    >
  </div>
</template>

<script>
export default {
  name: 'TableParser',
  data() {
    return {
      dragOver: false,
      uploadedFile: null,
      previewUrl: '',
      chatFiles: [],
      MAX_FILES: 3,
      latexResult: '',
      renderedImage: '',
      loading: false,
      mode: 'latex', // 'latex' or 'render'
      chatMessages: [
        { sender: 'bot', content: '您好，有什么可以帮您分析的表格？' }
      ],
      newMessage: ''
    }
  },
  computed: {
    formattedLatex() {
      return (this.latexResult || '').replace(/\\\\\\\\/g, '<br/>').replace(/\\\\/g, '\\');
      // return this.latexResult;
    }
  },
  methods: {
    // 文件上传相关方法
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    triggerChatFileInput() {
      this.$refs.chatFileInput.click()
    },
    handleFileChange(e) {
      const file = e.target.files[0]
      if (file) this.handleFile(file)
    },
    handleChatFileChange(e) {
      const files = Array.from(e.target.files)
      this.handleChatFiles(files)
    },
    handleDrop(e) {
      this.dragOver = false
      const file = e.dataTransfer.files[0]
      this.handleFile(file)
    },
    handleFile(file) {
      if (!file) return
      this.uploadedFile = file
      this.previewUrl = URL.createObjectURL(file)
    },
    handleChatFiles(files) {
      if (this.chatFiles.length + files.length > this.MAX_FILES) {
        alert(`最多只能上传${this.MAX_FILES}个文件`)
        return
      }
      this.chatFiles = [...this.chatFiles, ...files]
    },
    removeFile(index) {
      this.chatFiles.splice(index, 1)
    },

    // LaTeX 解析相关方法
    async requestParse(mode) {
      if (!this.uploadedFile) {
        alert('请先上传文件')
        return
      }
      
      this.loading = true
      this.mode = mode
      
      const formData = new FormData()
      formData.append('file', this.uploadedFile)

      try {
        const response = await fetch('/api/image2latex', {
          method: 'POST',
          body: formData
        })
        const data = await response.json()
        
        if (mode === 'latex') {
          // this.latexResult = data.text || '';
          // this.latexResult = String.raw`${data.text}` || '';
          this.latexResult = data.text;
          console.log("latexResult1:" + this.latexResult)
          this.latexResult = data.text.replace(/\\/g, '\\\\'); 
          console.log("latexResult2:" + this.latexResult)
                      
          this.renderedImage = `http://[240c:c983:4::3:1f1e]:8611${data.image}`
        } else {
          // this.renderedImage = `http://[240c:c983:4::3:1f1e]:8611${data.image}`
        }
      } catch (error) {
        console.error('解析出错:', error)
        this.latexResult = '解析出错'
      } finally {
        this.loading = false
      }
    },
    copyLatex() {
      navigator.clipboard.writeText(this.latexResult)
        .then(() => alert('已复制到剪贴板'))
        .catch(err => console.error('复制失败:', err))
    },
    downloadLatex() {
      // 实现下载逻辑
    },
    changeMode(mode){
      this.mode = mode
    },

    // 聊天相关方法
    sendMessage() {
      const message = this.newMessage.trim()
      if (!message && this.chatFiles.length === 0) {
        alert('请输入消息或上传文件')
        return
      }

      if (message) {
        this.addMessage(message, 'user')
        this.newMessage = ''
      }

      if (this.chatFiles.length > 0) {
        // 处理文件上传
        console.log('发送文件:', this.chatFiles)
        this.chatFiles = []
      }

      // 调用API获取回复
      this.getBotReply(message)
    },
    addMessage(content, sender) {
      this.chatMessages.push({
        sender,
        content
      })
      this.scrollChatToBottom()
    },
    async getBotReply(query) {
      if (!this.latexResult && !query) return
      
      // const formData = new FormData()
      // formData.append('latex', this.latexResult)
      // formData.append('query', query)

      try {
        const response = await fetch('/api/query', {
          method: 'POST',
           headers: {
                'Content-Type': 'application/json', // 明确指定JSON格式
                'accept': 'application/json'
      },
            body: JSON.stringify({
              latex: this.latexResult,
              query: query
      })
        })
        const data = await response.json()
        this.addMessage(data.answer || '抱歉，未收到回答', 'bot')
      } catch (error) {
        console.error('请求出错:', error)
        this.addMessage('出错了，请稍后重试', 'bot')
      }
    },
    scrollChatToBottom() {
      this.$nextTick(() => {
        const chatLog = this.$el.querySelector('.chat-log')
        if (chatLog) chatLog.scrollTop = chatLog.scrollHeight
      })
    }
  }
}
</script>

<style scoped>
/* 基础重置 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

/* 根元素设置 */
html, body {
  width: 100%;
  height: 100vh;
  margin: 0;
  overflow: hidden; /* 禁用全局滚动 */
  font-family: sans-serif;
}
.app-container{
  height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 顶部导航栏 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24px;
  height: 60px;
  background: #f5f5f5;
  border-bottom: 1px solid #ddd;
}

.header .title {
  font-size: 18px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

.header .logo {
  height: 36px;
  width: 36px;
  margin-right: 12px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-info .avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 12px;
}

.user-info .email {
  margin-right: 16px;
  color: #666;
}

/* 主体布局 */
.main-content {
  display: flex;
  height: calc(100vh - 60px - 30px - 15px); /* 视口高度 - 导航栏高度 - 底部间距 - 顶部padding */
  padding: 15px 0;
  margin-bottom: 30px; /* 底部间距 */
  box-sizing: border-box; /* 确保padding包含在高度计算内 */
  overflow: hidden; /* 禁止内容滚动 */
}

/* 上传区域 */
.upload-pane {
  width: 30%;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
  border-right: 1px solid #ddd;
  padding: 16px;
  display: flex;
  flex-direction: column;
  margin: 0 8px;
}

.drop-zone {
  flex: 0 0 160px;
  border: 2px dashed #ccc;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: #888;
  cursor: pointer;
  margin-bottom: 12px;
}

.drop-zone.hover {
  border-color: #888;
  color: #444;
}

.preview {
  flex: 1;
  overflow: auto;
  border: 1px solid #eee;
  padding: 8px;
}

.preview img {
  max-width: 100%;
  display: block;
  margin: 0 auto;
}

/* 中间区域 */
.center-pane {
  width: 40%;
  display: flex;
  flex-direction: column;
  padding: 16px;
  border-right: 1px solid #ddd;
  margin: 0 8px;
}

.controls {
  margin-bottom: 12px;
}

.control-btn {
  padding: 6px 12px;
  margin-right: 8px;
  border: 1px solid #ccc;
  background: #f9f9f9;
  border-radius: 4px;
  cursor: pointer;
}

.control-btn.active {
  background: #e0d4fc;
  border-color: #ab90eb;
}

.latex-render {
  flex: 1;
  overflow: auto;
  border: 1px solid #eee;
  padding: 12px;
  background: #fafafa;
}

/* 右侧聊天区域 */
.chat-pane {
  width: 30%;
  display: flex;
  flex-direction: column;
  padding: 16px;
  margin: 0 8px;
}

.chat-log {
  flex: 1;
  overflow: auto;
  border: 1px solid #eee;
  padding: 12px;
  background: #fefcf0;
}

.msg {
  margin-bottom: 12px;
  display: flex;
}

.msg.user {
  justify-content: flex-end;
}

.msg.bot {
  justify-content: flex-start;
}

.bubble {
  max-width: 80%;
  padding: 8px 12px;
  border-radius: 16px;
}

.msg.user .bubble {
  background: #cce5ff;
  color: #004085;
  border-bottom-right-radius: 4px;
}

.msg.bot .bubble {
  background: #fff3cd;
  color: #856404;
  border-bottom-left-radius: 4px;
  display: flex;
  align-items: flex-start;
}

.msg.bot .bubble img {
  width: 24px;
  height: 24px;
  border-radius: 50%;
  margin-right: 8px;
}

.chat-input {
  display: flex;
  margin-top: 8px;
}

.chat-text {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.send-btn {
  margin-left: 8px;
  padding: 8px 16px;
  border: none;
  background: #28a745;
  color: #fff;
  border-radius: 4px;
  cursor: pointer;
}

/* 图标容器 */
.icon-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.icon {
  width: 20px;
  height: 20px;
  fill: currentColor;
  cursor: pointer;
}

/* 隐藏元素 */
.hidden-input {
  display: none;
}
.latex-render > div {
  text-align: left;
  /* width: 100%; */
}
</style>